<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>02 broadcastChannel</title>
  <style>
    :root {
      font-size: 14px;
    }
    .container {
      margin: 2px;
      border: 1px solid #ccc;
      padding: 10px;
    }
    input {
      height: 36px;
    }
    textarea {
      width: 240px;
      height: 120px;
      padding: 5px;
    }
    .container input, .container textarea {
      font-size: 1.2rem;
    }
    #btn {
      width: 300px;
      height: 36px;
    }
  </style>
</head>
<body>
  <p>
    Broadcast Channel API 可以实现同源下浏览器不同窗口，
    Tab 页，frame 或者 iframe 下的(通常是同一个网站下不同的页面) 之间的简单通讯。
  </p>
  <div class="container">
    <p id="page"></p>
    <p><label >频道名：<input type="text" id="name" placeholder="请输入名称"  value="myChannel2" autocomplete="off"/></label>
      <br>
      <button onclick="craeteChannel()">创建</button> &nbsp;&nbsp; <button onclick="closeChannel()">注销</button>
    </p>
    <p>
      <label >内容：<textarea type="text" id="desc" placeholder="请输入内容" ></textarea></label>
    </p>
    <p><button id="btn" onclick="sendMsg()">提交</button></p>
  </div>
  
  <ul id="ul">

  </ul>

  <script>
    const btn = document.querySelector('#btn'),
          desc = document.querySelector('#desc'),
          channelName = document.querySelector('#name'),
          ul = document.querySelector('#ul'),
          curPage = document.querySelector('#page');

    const pageName = Math.random().toString(36).substr(2,3).toLocaleUpperCase();
    curPage.textContent = pageName;

    // 通过构造函数，传入频道名，即可创建或加入频道，如果该命名的频道不存在，则初始化并创建
    let channel;

    function craeteChannel() {
      // 创建或加入频道
      // const name = channelName.value
      if (channel) return;
      channel = new BroadcastChannel(channelName.value);
      channel.onmessage = (e) => {
        console.log(`${pageName}: ${e.data}`)
        insertLi(pageName, e.data)
      }

    }

    function closeChannel() {
      channel && channel.close();
      channel = null;
    }

    function sendMsg() {
      channel.postMessage(desc.value);
    }

    function insertLi(pageName, desc) {
      const time = new Date().toLocaleTimeString();

      const frag = document.createDocumentFragment();
      const li = document.createElement('li')
      li.innerHTML = `<span style="margin-right: 20px;">${pageName}：</span>${desc} <sup style="margin-left: 20px; color: #0011ff;">${time}</sup>`
      frag.appendChild(li);
      ul.appendChild(frag)
    }
    window.onbeforeunload = () => {
      // 关闭与共享线程的连接
      closeChannel()
      
    }
  </script>
</body>
</html>